package com.wyix;

import java.util.concurrent.CountDownLatch;

/**
 * @author wangdx
 * @since 2025/8/4
 */
public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        // 计数器为3（等待3个任务完成）
        CountDownLatch latch = new CountDownLatch(3);

        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                try {
                    System.out.println(Thread.currentThread().getName() + "子线程初始化...");
                    Thread.sleep(1000); // 模拟初始化耗时
                    System.out.println(Thread.currentThread().getName() + "子线程处理完成...");
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } finally {
                    latch.countDown(); // 计数器减1
                }
            }, "线程" + i).start();
        }

        latch.await(); // 主线程阻塞，直到计数器为0
        System.out.println("所有子线程初始化完成，主线程开始工作");
    }
}